<?php
/**
  * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说 图/谱/源/码/分/享
 */
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/31 0031
 * Time: 11:59
 */
defined("IN_IA")or exit("Access denied");
global $_GPC,$_W;
$uniacid=$_W['uniacid'];
$uid=$_GPC['uid'];
$op=$_GPC['op'] ? $_GPC['op'] :"apply_become_distribution";
include 'function.inc.php';
if($op=='apply_become_distribution'){
    $request=array();
    $filed=array('distribution_cover','distribution_agreement');
    $farmSetData=getFarmSetData($filed,array('uniacid'=>$uniacid));
    $request['farmSetData']=$farmSetData;
    echo json_encode($request);die;
}

//申请成为分销商
if($op=='apply_distribution'){
    if($uid) {
        $form_id=$_GPC['form_id'];
        //保存formid
        $form_id_data=array(
            'uid'=>$uid,
            'create_time'=>time(),
            'formid'=>$form_id,
            'openid'=>$_W['openid'],
        );
        pdo_insert('cqkundian_farm_form_id',$form_id_data);
        $distribution = pdo_get('cqkundian_farm_distribution_check', array('uniacid' => $uniacid, 'uid' => $uid));
        $filed = array('is_check_distribution');
        $farmSetData = getFarmSetData($filed, array('uniacid' => $uniacid));
        if (empty($distribution) || $distribution['status']==2) {
            $data = array(
                'uid' => $uid,
                'uniacid' => $uniacid,
                'username' => $_GPC['name'],
                'phone' => $_GPC['phone'],
                'create_time' => time(),
            );
            if ($farmSetData['is_check_distribution'] == 1) {  //免审核
                $data['status'] = 1;
                $res = pdo_insert('cqkundian_farm_distribution_check', $data);
                //修改用户信息
                $update_user = array(
                    'is_distributor' => 1,
                    'become_time' => time(),
                );
                $filepath=$_W['siteroot'].getcqrcode($uid);
                $update_user['share_qrcode']=$filepath;
                $res1=pdo_update('cqkundian_farm_user', $update_user, array('uniacid' => $uniacid, 'uid' => $uid));
                if($res && $res1){
                    echo json_encode(array('code'=>1,'msg'=>'您已成为分销商'));die;
                }else{
                    echo json_encode(array('code'=>0,'msg'=>'操作失败'));die;
                }

            } else {
                $data['status'] = 0;
                $res = pdo_insert('cqkundian_farm_distribution_check', $data);
                if($res){
                    echo json_encode(array('code'=>1,'msg'=>'请耐心等待管理员审核'));die;
                }else{
                    echo json_encode(array('code'=>0,'msg'=>'网络错误,请稍后重试'));die;
                }
            }
        }else{
            echo json_encode(array('code'=>4,'msg'=>'申请已提交过了，请耐心等待审核'));die;
        }
    }else{
        echo json_encode(array('code'=>4,'msg'=>'请先授权登录'));die;
    }
}
//获取分销用户信息
if($op=='getUserInfo'){
    $request=array();
    $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
    if($user['one_distributor']!=0){
        $one_distributor=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$user['one_distributor']));
        $user['one_distributor_name']=$one_distributor['nickname'];
    }
    $request['user']=$user;
    echo json_encode($request);die;
}

//绑定用户信息
if($op=='bindParent'){
    $user_uid=$_GPC['user_uid'];
    $sale=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$user_uid));
    //判断当前分享人是否为分销商
    if($sale['is_distributor']==1){  //是分销商
        //判断当前登录用户是否为分销商
        $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
        if($user['is_distributor']!=1){ //不是分销商
            if($user['one_distributor']==0 || $user['one_distributor']==''){
                //当前登录用户没有推荐人->修改当前用户的一级分销商为user_uid
                $res=pdo_update('cqkundian_farm_user',array('one_distributor'=>$user_uid),array('uniacid'=>$uniacid,'uid'=>$uid));
                if($res){
                    echo json_encode(array('code'=>0));die;
                }else{
                    echo json_encode(array('code'=>1));die;
                }
            }else{
                echo json_encode(array('code'=>0,'msg'=>'当前用户已成为其他分销商下线'));
            }
        }else{
            echo json_encode(array('code'=>0,'msg'=>'当前登录用户已是分销商'));
        }
    }else{
        echo json_encode(array('code'=>0,'msg'=>'当前分享人不是分销商'));
    }
}

//获取分销订单信息
if($op=='getSaleOrder'){
    $request=array();
    $status=$_GPC['status'];
    $page=$_GPC['page'];
    $order_type=$_GPC['order_type'];
    $uids=array();
    $one_uids=array();
    //我的所有一级分销商
    $one_sale=pdo_getall('cqkundian_farm_user',array('uniacid'=>$uniacid,'one_distributor'=>$uid),array('uid'));
    if(!empty($one_sale)) {
        for ($i = 0; $i < count($one_sale); $i++) {
            $uids[] = $one_sale[$i]['uid'];
            $one_uids[] = $one_sale[$i]['uid'];     //一级分销商
            $two_sale = pdo_getall('cqkundian_farm_user', array('uniacid' => $uniacid, 'one_distributor' => $one_sale[$i]['uid']),array('uid'));
            if(!empty($two_sale)) {
                for ($j = 0; $j < count($two_sale); $j++) {
                    $uids[] = $two_sale[$j]['uid'];
                }
            }
        }
    }

    //查询所有分销商的订单
    $order_con=array(
        'uniacid'=>$uniacid,
        'uid in'=>$uids,
        'use_is_delete'=>0,
        'is_price >'=>0
    );
    if($status!=6){
        if($status==1){
            $order_con['status in']=array(1,2);
        }else {
            $order_con['status'] = $status;
        }
    }
    $orderData=array();
    if($order_type==1) {
        $orderData = pdo_getall('cqkundian_farm_shop_order', $order_con, '', '', 'create_time desc', array($page, 10));
        for ($m = 0; $m < count($orderData); $m++) {
            $orderData[$m]['sale_parent'] = 2;
            $orderData[$m]['count'] = 0;
            for ($n = 0; $n < count($one_uids); $n++) {
                if ($orderData[$m]['uid'] == $one_uids[$n]) {
                    $orderData[$m]['sale_parent'] = 1;
                    break;
                }
            }

            //查询订单详细信息
            $orderDetail = pdo_getall('cqkundian_farm_shop_order_detail', array('uniacid' => $uniacid, 'order_id' => $orderData[$m]['id']));
            for ($h = 0; $h < count($orderDetail); $h++) {
                $orderData[$m]['count'] += $orderDetail[$h]['count'];
            }
            $orderData[$m]['orderDetail'] = $orderDetail;
            $orderData[$m]['click'] = false;
            //查询用户信息
            $user = pdo_get('cqkundian_farm_user', array('uid' => $orderData[$m]['uid'], 'uniacid' => $uniacid));
            $orderData[$m]['nickname'] = $user['nickname'];
            $orderData[$m]['avatarurl'] = $user['avatarurl'];
        }
    }elseif ($order_type==2){
        $orderData = pdo_getall('cqkundian_farm_group_order', $order_con, '', '', 'create_time desc', array($page, 10));
        for ($m = 0; $m < count($orderData); $m++) {
            $orderData[$m]['sale_parent'] = 2;
            $orderData[$m]['count'] = 0;
            for ($n = 0; $n < count($one_uids); $n++) {
                if ($orderData[$m]['uid'] == $one_uids[$n]) {
                    $orderData[$m]['sale_parent'] = 1;
                    break;
                }
            }
            //查询订单详细信息
            $orderDetail = pdo_getall('cqkundian_farm_group_order_detail', array('uniacid' => $uniacid, 'order_id' => $orderData[$m]['id']));
            for ($h = 0; $h < count($orderDetail); $h++) {
                $orderData[$m]['count'] += $orderDetail[$h]['count'];
            }
            $orderData[$m]['orderDetail'] = $orderDetail;
            $orderData[$m]['click'] = false;
            //查询用户信息
            $user = pdo_get('cqkundian_farm_user', array('uid' => $orderData[$m]['uid'], 'uniacid' => $uniacid));
            $orderData[$m]['nickname'] = $user['nickname'];
            $orderData[$m]['avatarurl'] = $user['avatarurl'];
        }
    }elseif ($order_type==3){
        $animal_con=array(
            'uniacid'=>$uniacid,
            'uid in'=>$uids,
            'is_price >'=>0
        );
        if($status!=6){
            if($status==1){
                $animal_con['status in']=array(1,2);
            }else {
                $animal_con['status'] = $status;
            }
        }
        $orderData = pdo_getall('cqkundian_farm_animal_order', $animal_con, '', '', 'create_time desc', array($page, 10));
        for ($m = 0; $m < count($orderData); $m++) {
            $orderData[$m]['sale_parent'] = 2;
            for ($n = 0; $n < count($one_uids); $n++) {
                if ($orderData[$m]['uid'] == $one_uids[$n]) {
                    $orderData[$m]['sale_parent'] = 1;
                    break;
                }
            }
            //查询订单详细信息
            $orderDetail = pdo_get('cqkundian_farm_animal', array('uniacid' => $uniacid, 'id' => $orderData[$m]['aid']));
            $orderData[$m]['orderDetail'] = $orderDetail;
            $orderData[$m]['click'] = false;
            //查询用户信息
            $user = pdo_get('cqkundian_farm_user', array('uid' => $orderData[$m]['uid'], 'uniacid' => $uniacid));
            $orderData[$m]['nickname'] = $user['nickname'];
            $orderData[$m]['avatarurl'] = $user['avatarurl'];
        }
    }elseif ($order_type==4){
        $land_con=array(
            'uniacid'=>$uniacid,
            'uid in'=>$uids,
            'is_price >'=>0
        );
        if($status!=6){
            if($status==1 || $status==3){
                $land_con['status in']=array(1,2);
            }else {
                $land_con['status'] = $status;
            }
        }
        $orderData = pdo_getall('cqkundian_farm_land_order', $land_con, '', '', 'create_time desc', array($page, 10));
        for ($m = 0; $m < count($orderData); $m++) {
            $orderData[$m]['sale_parent'] = 2;
            $orderData[$m]['count']=0;
            for ($n = 0; $n < count($one_uids); $n++) {
                if ($orderData[$m]['uid'] == $one_uids[$n]) {
                    $orderData[$m]['sale_parent'] = 1;
                    break;
                }
            }
            //查询订单详细信息
            $orderDetail = pdo_getall('cqkundian_farm_land_order_detail', array('uniacid' => $uniacid, 'order_id' => $orderData[$m]['id']));
            for ($h = 0; $h < count($orderDetail); $h++) {
                $orderData[$m]['count'] += $orderDetail[$h]['land_count'];
            }
            $orderData[$m]['orderDetail'] = $orderDetail;
            $orderData[$m]['click'] = false;
            //查询用户信息
            $user = pdo_get('cqkundian_farm_user', array('uid' => $orderData[$m]['uid'], 'uniacid' => $uniacid));
            $orderData[$m]['nickname'] = $user['nickname'];
            $orderData[$m]['avatarurl'] = $user['avatarurl'];
        }
    }
    $request['orderData']=$orderData;
    echo json_encode($request);die;

}

//获取分销设置
if($op=='getSaleSetting'){
    $request=array();
    $saleSetting=getFarmSetData(array('distribution_withdraw_low_price'),array('uniacid'=>$uniacid));
    $request['saleSetting']=$saleSetting;
    $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
    $request['user']=$user;
    echo json_encode($request);die;
}

//申请提现
if($op=='sale_withdraw'){
    $price=$_GPC['price'];
    $wx_account=$_GPC['phone'];
    $name=$_GPC['name'];
    $saleSetting=getFarmSetData(array('distribution_withdraw_low_price'),array('uniacid'=>$uniacid));
    if($saleSetting['distribution_withdraw_low_price']>$price){
        echo json_encode(array('code'=>1,'msg'=>'体现金额不能低于'.$saleSetting['distribution_withdraw_low_price'].'元'));die;
    }else{
        $data=array(
            'uid'=>$uid,
            'uniacid'=>$uniacid,
            'name'=>$name,
            'wx_account'=>$wx_account,
            'create_time'=>time(),
            'price'=>$price,
            'status'=>0,
        );
        $res=pdo_insert('cqkundian_farm_withdraw',$data);
        $res1=pdo_update('cqkundian_farm_user',array('price -='=>$price),array('uid'=>$uid,'uniacid'=>$uniacid));
        if($res && $res1){
            echo json_encode(array('code'=>1,'msg'=>'体现申请已提交！'));die;
        }else{
            echo json_encode(array('code'=>2,'msg'=>'体现申请提交失败，请稍后重试'));
        }
    }
}


//获取体现记录
if($op=='getWithdrawRecord'){
    $request=array();
    $page=$_GPC['page'];
    $status=$_GPC['status'];
    $con=array('uniacid'=>$uniacid,'uid'=>$uid);
    if($status!=-1){
        $con['status']=$status;
    }
    $list=pdo_getall('cqkundian_farm_withdraw',$con,'','','create_time desc',array($page,15));
    for ($i=0;$i<count($list);$i++){
        $list[$i]['create_time']=date("Y-m-d H:i:s",$list[$i]['create_time']);
    }
    $request['list']=$list;
    echo json_encode($request);die;
}

//获取用户的佣金信息
if($op=='getUserSalePrice'){
    $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
    if($user['total_price']==''){
        $user['total_price']=0;
    }
    $user['yi_send_price']=$user['total_price']-$user['price'];

    //计算带打款佣金
    $dai_price=0;
    $record=pdo_getall('cqkundian_farm_withdraw',array('uniacid'=>$uniacid,'uid'=>$uid,'status'=>0));
    for ($i=0;$i<count($record);$i++){
        $dai_price+=$record[$i]['price'];
    }
    $user['dai_price']=$dai_price;
    echo json_encode(array('user'=>$user));die;
}

//获取团队信息
if($op=='getSaleTeam'){
    $request=array();
    $current=$_GPC['current'];
    if(empty($_GPC['page'])){
        $page=1;
    }else{
        $page=$_GPC['page'];
    }
    //获取一级分销
    $one_sale=pdo_getall('cqkundian_farm_user',array('one_distributor'=>$uid,'uniacid'=>$uniacid),'','','become_time desc',array($page,10));
    if($current==1) {
        $one_sale=getSaleData($one_sale,$uniacid);
        $request['one_sale']=$one_sale;
    }elseif ($current==2){
        $two_uids=array();
        for ($i=0;$i<count($one_sale);$i++){
            $two_uids=$one_sale[$i]['uid'];
        }

        $two_sale=pdo_getall('cqkundian_farm_user',array('one_distributor in'=>$two_uids,'uniacid'=>$uniacid),'','','become_time desc',array($page,10));
        $two_sale=getSaleData($two_sale,$uniacid);
        $request['one_sale']=$two_sale;
    }

    echo json_encode($request);die;
}

//获取分销二维码
if($op=='getQrcode'){
    $user=pdo_get('cqkundian_farm_user',array('uid'=>$uid,'uniacid'=>$uniacid));
    if($user['share_qrcode']==''){
        $filepath=$_W['siteroot'].getcqrcode($uid);
        pdo_update('cqkundian_farm_user',array('share_qrcode'=>$filepath),array('uid'=>$uid,'uniacid'=>$uniacid));
        $user['share_qrcode']=$filepath;
    }
    echo json_encode(array('user'=>$user));die;
}


/**
 * 组合查询下线分销商
 * @param $one_sale
 * @param $uniacid
 * @return mixed
 */
function getSaleData($one_sale,$uniacid){
    for ($i = 0; $i < count($one_sale); $i++) {
        $one_sale[$i]['total_price'] = 0;
        $shop_order = pdo_getall('cqkundian_farm_shop_order', array('uniacid' => $uniacid, 'uid' => $one_sale[$i]['uid'], 'is_price >' => 0, 'status' => 3));
        for ($m = 1; $m < count($shop_order); $m++) {
            $one_sale[$i]['total_price'] += $shop_order[$m]['total_price'];
        }
        $group_order = pdo_getall('cqkundian_farm_group_order', array('uniacid' => $uniacid, 'uid' => $one_sale[$i]['uid'], 'is_price >' => 0, 'status' => 3));
        for ($g = 0; $g < count($group_order); $g++) {
            $one_sale[$i]['total_price'] += $group_order[$g]['total_price'];
        }

        $animal_order = pdo_getall('cqkundian_farm_animal_order', array('uniacid' => $uniacid, 'uid' => $one_sale[$i]['uid'], 'is_price >' => 0, 'status' => 1));
        for ($a = 0; $a < count($animal_order); $a++) {
            $one_sale[$i]['total_price'] += $animal_order[$a]['total_price'];
        }
        $land_order = pdo_getall('cqkundian_farm_land_order', array('uniacid' => $uniacid, 'uid' => $one_sale[$i]['uid'], 'is_price >' => 0, 'status' => 1));
        for ($b = 0; $b < count($land_order); $b++) {
            $one_sale[$i]['total_price'] += $land_order[$b]['total_price'];
        }
        $one_sale[$i]['become_time'] = date("Y-m-d", $one_sale[$i]['become_time']);


        $user_total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('cqkundian_farm_user') . " WHERE one_distributor=:one_distributor AND uniacid=:uniacid ", array(":one_distributor" => $one_sale[$i]['uid'], ":uniacid" => $uniacid));
        $one_sale[$i]['one_sale_user'] = $user_total;
    }

    return $one_sale;
}


/**
 * 生成分享二维码
 * @param $uid
 * @return string
 */
function getcqrcode($uid){
    $page="kundian_farm/pages/HomePage/index/index?uid=".$uid;
    $account_api = WeAccount::create();
    $response = $account_api->getCodeLimit($page, 430, array(
        'auto_color' => false,
        'line_color' => array(
            'r' => '#ABABAB',
            'g' => '#ABABAC',
            'b' => '#ABABAD',
        ),
    ));
    $filename='kundian_farm_share_uid_'.$uid;
    $filepath='/addons/kundian_farm/resource/image/'.$filename.'.png';
    file_put_contents(IA_ROOT . '/addons/kundian_farm/resource/image/'.$filename.'.png', $response);
    return $filepath;
}